package kvoog.arkanoid.screens;

import kvoog.arkanoid.core.ArkanoidEntityFactory;
import kvoog.arkanoid.core.KvoogGame;
import kvoog.arkanoid.common.EntityBuilder;
import kvoog.arkanoid.core.InputSystem;
import kvoog.arkanoid.physics.BodyBuilder;
import kvoog.arkanoid.physics.CollisionResponseSystem;
import kvoog.arkanoid.physics.PhysicsSystem;
import kvoog.arkanoid.rendering.BackgroundRenderingSystem;
import kvoog.arkanoid.rendering.HudRenderingSystem;
import kvoog.arkanoid.rendering.SpriteRenderingSystem;

import com.artemis.managers.GroupManager;
import com.artemis.managers.PlayerManager;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.GLCommon;
import com.badlogic.gdx.math.Vector2;

public class GameScreen extends KvoogScreen {

	private com.artemis.World ecsWorld;

	public GameScreen(KvoogGame game) {
		super(game);
		
		ecsWorld = new com.artemis.World();
		
		ecsWorld.setManager(new PlayerManager());
		ecsWorld.setManager(new GroupManager());
		
		ecsWorld.setSystem(new InputSystem());
				
		com.badlogic.gdx.physics.box2d.World.setVelocityThreshold(0f);
		com.badlogic.gdx.physics.box2d.World physicsWorld = new com.badlogic.gdx.physics.box2d.World(new Vector2(0, 0), true);
		ecsWorld.setSystem(new PhysicsSystem(physicsWorld));
		ecsWorld.setSystem(new CollisionResponseSystem());

		ecsWorld.setSystem(new BackgroundRenderingSystem(this.getSpriteBatch()));
		ecsWorld.setSystem(new SpriteRenderingSystem(this.getSpriteBatch()));
		ecsWorld.setSystem(new HudRenderingSystem(this.getSpriteBatch()));
		
		ecsWorld.initialize();
		
		ArkanoidEntityFactory.getInstance().setEntityBuilder(new EntityBuilder(ecsWorld));
		ArkanoidEntityFactory.getInstance().setBodyBuilder(new BodyBuilder(physicsWorld));
		
		generateLevel();
	}

	@Override
	public void render(float delta) {
		// Were doing custom rendering		
		//super.render(delta);
		
		GLCommon gl = Gdx.graphics.getGLCommon();
		gl.glClearColor(0, 0, 0, 0);
		gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		
		ecsWorld.setDelta(delta);
		ecsWorld.process();
	}
	
	private void generateLevel() {
		
		ArkanoidEntityFactory.getInstance().createPad(4f, 0.3f, 1f, 0.2f);
		
		ArkanoidEntityFactory.getInstance().createBall(4f, 1f, 0.07f);

		Vector2[] vecs = new Vector2[] {
			new Vector2(0, 0),
			new Vector2(0, 4.8f),
			new Vector2(8, 4.8f),
			new Vector2(8, 0)
		};
		
		ArkanoidEntityFactory.getInstance().createBounds(vecs);
		ArkanoidEntityFactory.getInstance().createTrigger(4, -0.5f, 8, 1.1f);
	
		int brick_num_hor = 15;
		float brick_width = 8f/brick_num_hor;
		int brick_num_ver = 8;
		float brick_height = 4.8f/3/brick_num_ver;
		
		for (int i = 0; i < brick_num_hor; i++)
			for (int j = 0; j < brick_num_ver; j++)
				ArkanoidEntityFactory.getInstance().createBrick(i*brick_width+brick_width/2f, 4-(j*brick_height+brick_height/2f), brick_width, brick_height);
	}
	
}
